import re

import logging
from datetime import datetime

from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render_to_response
from google.appengine.api import users
from google.appengine.ext import db
from google.appengine.api.urlfetch import fetch

import models_common as models
from views_common import *
import Classifier

import simplejson

###########################################################################################################################
# /chat/
# GET
def index(request):
    user = getUser()
    msgs = models.Message.all().filter('author = ', user).order('-created_on').fetch(10)
    
    clss = models.Classification.all()
    
    url_linktext, url = getLoginAndUrl(request)
    
    user_email = user.email()
    
    admin = "user"
    if user_email == "ldmiao@gmail.com" or user_email == "zhaoyong04@gmail.com":
        admin = "admin"
    
    payload = {'msgs': reversed(msgs), 'clss': clss, 'url_linktext': url_linktext, 'url': url, 'user' : user, 'usrs': getAllUsers(), 'admin': admin, }
    
    return render('chat_index.html', payload)
    
###########################################################################################################################
# /chat/add/
# POST
# *message : message of the Message
# *email : email of the current User
def add(request):
    message = request.POST['message']
    email = request.POST['email']
    message = message.rstrip()
    
    message = unicode(message, 'utf-8').rstrip(" \n")
    #message = urllib.unquote(message)
    
    if not message or message == "":
        return None
    
    msg = models.Message(message=message, author=getUser(email))
    
    
    
    msg.put()

    clss = models.Classification.all()
    #return HttpResponse(msg.htmlMsg())
    payload = {'msg': msg, 'clss': clss, }
    return render('chat_item.html', payload)
    
###########################################################################################################################
# /chat/edit/
# POST
# *msgkey : key of the Message
# *message : message of the Message
def edit(request):
    msgkey = request.POST['msgkey']
    msg = models.Message.get(msgkey)
    
    if msg.author == getUser():
        message = request.POST['message']
        message = unicode(message, 'utf-8').rstrip(" \n")
        msg.message = message
        msg.put()
        
        return HttpResponse(msgkey+","+msg.markedHtmlMsg())
    else:
        return HttpResponse("error!"+"Sorry, You are not authorized to do this.")

###########################################################################################################################
# /chat/update/
# POST
# *msgkey : key of the last Message
# *clskey : key of the Classificaiton
def update(request):
    msgkey = request.POST['msgkey']
    clskey = request.POST['clskey']
    
    user = getUser()
    msgs = models.Message.all().filter('author = ', user)
    
    if msgkey and msgkey != "None":
        lastmsg = models.Message.get(msgkey)
        if lastmsg:
            msgs = msgs.filter('created_on > ', lastmsg.created_on)
        
    if clskey and clskey != "None":
        if clskey == "notmarked":
            msgs = msgs.filter('classification = ', None)
        else:
            cls = models.Classification.get(clskey)
            if cls:
                msgs = msgs.filter('classification = ', cls)
        
    msgs = msgs.order('-created_on').fetch(10)
    
    payload = {'msgs': reversed(msgs), }
    
    return render('chat_items.html', payload)

###########################################################################################################################
# /chat/previous/
# POST
# *msgkey : key of the first Message
# *clskey : key of the Classificaiton
def previous(request):
    msgkey = request.POST['msgkey']
    clskey = request.POST['clskey']
    
    logging.info("clskey:"+clskey)
    logging.info("msgkey:"+msgkey)
    
    user = getUser()
    msgs = models.Message.all().filter('author = ', user)
    
    if clskey and clskey != "None":
        if clskey == "notmarked":
            msgs = msgs.filter('classification = ', None)
        else:
            cls = models.Classification.get(clskey)
            if cls:
                logging.info("class name:"+cls.name)
                msgs = msgs.filter('classification = ', cls)
    
    #msgs = msgs.filter('created_on <= ', datetime.utcnow())
    
    if msgkey and msgkey != "None":
        firstmsg = models.Message.get(msgkey)
        
        if firstmsg:
            logging.info("firstmsg.created_on:"+firstmsg.created_on.strftime("%Y-%m-%d %H:%M:%S"))
            msgs = msgs.filter('created_on < ', firstmsg.created_on)
        
    msgs = msgs.order('-created_on').fetch(10)
    
    payload = {'msgs': reversed(msgs), }
    
    return render('chat_items.html', payload)

###########################################################################################################################
# /chat/addclass/
# POST
# *name : name of the Classification
# *iconcolor : iconcolor of the Classification
def addclass(request):
    user_email = getUser().email()
    if user_email == "ldmiao@gmail.com" or user_email == "zhaoyong04@gmail.com":
        name = request.POST['name']
        iconcolor = request.POST['iconcolor']
        #description = request.POST['description']
        cls = models.Classification(name=name, iconcolor=iconcolor)
        cls.put()
        
        payload = {'cls': cls, }
        return render('class_item.html', payload)
    return HttpResponse("error!"+"Sorry, You are not authorized to do this.")
    
###########################################################################################################################
# /chat/mark/
# POST
# *msgkey : key of the Message
# *clskey : key of the Classificaiton
def mark(request):
    msgkey = request.POST['msgkey']
    msg = db.get(msgkey)
    
    if msg.author == getUser():
        clskey = request.POST['clskey']
        cls = None
        if clskey != "notmarked":
            cls = db.get(clskey)
        
        msg.classification = cls
        msg.put()
        
        if cls:
            #addToAccounting(msg)
            return HttpResponse(str(msg.key())+","+str(cls.key())+","+cls.iconcolor+","+cls.name)
        else:
            return HttpResponse(str(msg.key())+",notmarked,blue,None")
    else:
        return HttpResponse("error!"+"Sorry, You are not authorized to do this.")

###########################################################################################################################
# /chat/botstatus/
# POST
# *url : key of the Message
def botstatus(request):
    url = request.POST['url']
    response = fetch(url)
    content = response.content
    match_obj = re.search("""<img src="/talk/service/resources/blank.gif" height="9" width="9" alt="">\s*(.*?)</div>""", content, re.DOTALL)
    status = "Checking..."
    if match_obj:
        status = match_obj.group(1)
    return HttpResponse(status)

###########################################################################################################################

# /chat/json/
# GET
# *url : key of the Message
def json(request):
    #logging.info("xxxxxxxxxx")
    
    data = request.POST['data']
    #logging.info(data)
    return HttpResponse(simplejson.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}]))

###########################################################################################################################
